/*****目标团队--目标 --攻防赛*****/
<template><!---->
  <search-table
	    ref="searchTable"
		  :columns="targetTeamCol" 
      :data="targetAllotList"
      :total="targetAllotTotal"
      :page.sync="queryTargetAllotInfo.pageIndex"
      :size.sync="queryTargetAllotInfo.pageSize"
      @change-size="getTargetSize"
      @change-page="getTargetPage"
	>
  <template slot="search">
    <div class="targetHeader">
      <Button  type='primary'  ghost @click="showAddAndUpdate('')" :disabled="formValidate.accessGroupList.length == 0 || disabledAllBtn" style="margin-right:15px;"><img src="../../../../assets/scene/target-allot-purple.png" alt="" />目标分配</Button>
      <Select filterable v-model="queryTargetAllotInfo.teamName" style="width:150px;margin-right:15px;"
          @on-change="getTargetPage(1)" transfer clearable placeholder="请选择团队">
        <Option v-for="item in formValidate.accessGroupList" :value="item.name" :key="item.id" :title="item.name">{{ item.name }}</Option>
      </Select>
      <Select filterable v-model="queryTargetAllotInfo.industry" placeholder="请选择行业" filterable clearable style="width:150px;margin-right:15px;" @on-change="getTargetPage(1)">
        <Option :value="item.dictid" v-for="item in industryList" :key="item.dictid" :title="item.dictname">{{item.dictname}}</Option>
      </Select>
      <Input v-model.trim="queryTargetAllotInfo.company" placeholder="单位" style="width:180px;margin-right:15px;" @on-change="getTargetPage(1)"></Input>
      <Input v-model.trim="queryTargetAllotInfo.url" placeholder="Url" style="width:180px;margin-right:15px;" @on-change="getTargetPage(1)"></Input>
      <Modal v-model="targetModal.show" 
        :title="targetModal.title" 
        :loading = "targetModal.loading"
        width="800px" 
        class="account-target-modal"
        :mask-closable = "false"
        @on-visible-change="targetModalVisibleChange"
        @on-cancel="closeTargetModal"
        @on-ok="targetAllot">
        <div class="search-group">
          <Input v-model.trim="teamName" placeholder="团队名称" style="width:150px;margin-left:16px;" @on-change="getDataBounce"></Input>
          <Select filterable v-model="queryTargetTeamInfo.industry" placeholder="请选择行业" transfer filterable clearable style="width:150px;margin-left:16px;" @on-change="getTargetTeamList()">
            <Option :value="item.dictid" v-for="item in industryList" :key="item.dictid" :title="item.dictname">{{item.dictname}}</Option>
          </Select>
        </div>
        <Form ref="formValidate" :model="formValidate" :label-width="100">
          <!--{{formValidate.accessGroupList}}-->
          <div v-for="(group,index) in formValidate.accessGroupList" :key="index">
              <FormItem label="团队">
                {{group.name}}
                <!--<Select filterable  v-model="formValidate[$index].teamId" placeholder="请选择团队">
                  <Option  v-for="item in accessGroupList" :value="item.id"  :key="item.id">{{item.name}}</Option>
                </Select>-->
              </FormItem>
            <FormItem label="已选择目标">
                <Row><Tag color="blue" v-for="targetId in group.targetIds" :key="targetId">{{idwithName[targetId] && idwithName[targetId].company}}</Tag></Row>
              </FormItem>
            <FormItem label="所有目标" :prop="'accessGroupList.'+index+'.targetIds'">
                <!--<Select filterable v-model="group.targetIds" placeholder="请选择目标" multiple filterable> 
                  <Option  v-for="target in targetTeamData" :value="target.id" :key="target.id">{{target.company}}</Option>
                </Select>-->
                <Row>
                  <Input v-model.trim="group.queryCompany" placeholder="名称" style="width:150px" clearable @on-change="changeTargetTeamPage(1,group)"></Input>
                  <Page  show-elevator :total="targetTeamTotal" :current="group.queryPage" :page-size="queryTargetTeamInfo.pageSize" @on-change="changeTargetTeamPage($event,group)" show-total size="small" style="float:right"/>
                </Row>
                <CheckboxGroup v-model="group.targetIds" @on-change="changeCompanySelect($event,group)">
                <Checkbox :label="target.id" v-for="target in group.targetTeamData" :key="target.id">
                    <span>{{target.company}}</span>
                </Checkbox>
            </CheckboxGroup>
            </FormItem>
            <Divider dashed style="margin:10px 0"></Divider>
          </div>
        </Form>
      </Modal>
      <!--<Modal v-model="modifyTargetModal.show" 
        :title="modifyTargetModal.title" 
        :loading = "modifyTargetModal.loading"
        width="600px" 
        :mask-closable = "false"
        @on-cancel="handleReset('allotFormValidate')"
        @on-ok="modifyTargetAllot">
        <Form ref="allotFormValidate" :model="allotFormValidate" :rules="ruleValidate" :label-width="100">
          <FormItem label="目标" prop="basicTargetId">
            <Select filterable v-model="allotFormValidate.basicTargetId" placeholder="请选择目标" @on-change="changeTarget" filterable> 
              <Option  v-for="target in targetTeamData" :value="target.id" :key="target.id">{{target.name}}</Option>
            </Select>
          </FormItem>
          <FormItem label="团队" prop="teamId">
            <Select filterable  v-model="allotFormValidate.teamId" placeholder="请选择团队">
              <Option  v-for="item in accessGroupList" :value="item.id"  :key="item.id">{{item.name}}</Option>
            </Select>
          </FormItem>
          <FormItem label="子网络" prop="subnetId">
            <Select filterable  v-model="allotFormValidate.subnetId" placeholder="请选择子网络" @on-change="changeSubnet">
              <! --<Option value="all">所有</Option>-->
              <!--<Option  v-for="item in subnetList" :value="item.id"  :key="item.id">{{item.name}}</Option>
            </Select>
          </FormItem>
          <FormItem label="虚拟机" prop="vmId" v-if="modifyTargetModal.show">
            <Select filterable v-model="allotFormValidate.vmId" placeholder="请选择虚拟机" filterable>
              <Option v-for="item in vmlists" :value="item.id" :key="item.id">{{item.name}}</Option>
            </Select>
          </FormItem>
          <FormItem  label="是否显示" prop="visibility">
            <RadioGroup v-model="allotFormValidate.visibility">
              <Radio :label=1>显示</Radio>
              <Radio :label=0>不显示</Radio>
            </RadioGroup>
            <span style="color:#f90" v-if="type == 4"> <Icon type="ios-information-circle-outline"/>用于在演练页面的展示控制</span>
            <span style="color:#f90" v-if="type == 1"> <Icon type="ios-information-circle-outline"/>用于在竞赛页面的展示控制</span>
          </FormItem>
        </Form>
      </Modal>-->
      <!--<DatePicker format="yyyy-MM-dd HH:mm:ss" type="daterange"  placeholder="选择日期" style="width: 200px"
                  @on-change="searchTargetPrjD"></DatePicker>-->
      <!--<Input v-model.trim="searchPrjString" search placeholder="目标名称" style="width: 200px" @on-search="searchTargetPrj"  />-->
      <!-- <Page :total=	targetAllotTotal
            show-total show-elevator @on-page-size-change="getTargetSize"
      :current="queryTargetAllotInfo.pageIndex"
            @on-change="getTargetPage" style="float: right">
      </Page> -->
    </div>
  </template>
    <Modal v-model="targetModal.show" 
        :title="targetModal.title" 
        :loading = "targetModal.loading"
        width="800px" 
        class="account-target-modal"
        :mask-closable = "false"
        @on-visible-change="targetModalVisibleChange"
        @on-cancel="closeTargetModal"
        @on-ok="targetAllot">
        <div class="search-group">
          <Input v-model.trim="teamName" placeholder="团队名称" style="width:150px;margin-left:16px;" @on-change="getDataBounce"></Input>
          <Select filterable v-model="queryTargetTeamInfo.industry" placeholder="请选择行业" transfer filterable clearable style="width:150px;margin-left:16px;" @on-change="getTargetTeamList()">
            <Option :value="item.dictid" v-for="item in industryList" :key="item.dictid" :title="item.dictname">{{item.dictname}}</Option>
          </Select>
        </div>
        <Form ref="formValidate" :model="formValidate" :label-width="100">
          <!--{{formValidate.accessGroupList}}-->
          <div v-for="(group,index) in formValidate.accessGroupList" :key="index">
              <FormItem label="团队">
                {{group.name}}
                <!--<Select filterable  v-model="formValidate[$index].teamId" placeholder="请选择团队">
                  <Option  v-for="item in accessGroupList" :value="item.id"  :key="item.id">{{item.name}}</Option>
                </Select>-->
              </FormItem>
            <FormItem label="已选择目标">
                <Row><Tag color="blue" v-for="targetId in group.targetIds" :key="targetId">{{idwithName[targetId] && idwithName[targetId].company}}</Tag></Row>
              </FormItem>
            <FormItem label="所有目标" :prop="'accessGroupList.'+index+'.targetIds'">
                <!--<Select filterable v-model="group.targetIds" placeholder="请选择目标" multiple filterable> 
                  <Option  v-for="target in targetTeamData" :value="target.id" :key="target.id">{{target.company}}</Option>
                </Select>-->
                <Row>
                  <Input v-model.trim="group.queryCompany" placeholder="名称" style="width:150px" clearable @on-change="changeTargetTeamPage(1,group)"></Input>
                  <Page  show-elevator :total="targetTeamTotal" :current="group.queryPage" :page-size="queryTargetTeamInfo.pageSize" @on-change="changeTargetTeamPage($event,group)" show-total size="small" style="float:right"/>
                </Row>
                <CheckboxGroup v-model="group.targetIds" @on-change="changeCompanySelect($event,group)">
                <Checkbox :label="target.id" v-for="target in group.targetTeamData" :key="target.id">
                    <span>{{target.company}}</span>
                </Checkbox>
            </CheckboxGroup>
            </FormItem>
            <Divider dashed style="margin:10px 0"></Divider>
          </div>
        </Form>
      </Modal>
      <!--<Modal v-model="modifyTargetModal.show" 
        :title="modifyTargetModal.title" 
        :loading = "modifyTargetModal.loading"
        width="600px" 
        :mask-closable = "false"
        @on-cancel="handleReset('allotFormValidate')"
        @on-ok="modifyTargetAllot">
        <Form ref="allotFormValidate" :model="allotFormValidate" :rules="ruleValidate" :label-width="100">
          <FormItem label="目标" prop="basicTargetId">
            <Select filterable v-model="allotFormValidate.basicTargetId" placeholder="请选择目标" @on-change="changeTarget" filterable> 
              <Option  v-for="target in targetTeamData" :value="target.id" :key="target.id">{{target.name}}</Option>
            </Select>
          </FormItem>
          <FormItem label="团队" prop="teamId">
            <Select filterable  v-model="allotFormValidate.teamId" placeholder="请选择团队">
              <Option  v-for="item in accessGroupList" :value="item.id"  :key="item.id">{{item.name}}</Option>
            </Select>
          </FormItem>
          <FormItem label="子网络" prop="subnetId">
            <Select filterable  v-model="allotFormValidate.subnetId" placeholder="请选择子网络" @on-change="changeSubnet">
              <! --<Option value="all">所有</Option>-->
              <!--<Option  v-for="item in subnetList" :value="item.id"  :key="item.id">{{item.name}}</Option>
            </Select>
          </FormItem>
          <FormItem label="虚拟机" prop="vmId" v-if="modifyTargetModal.show">
            <Select filterable v-model="allotFormValidate.vmId" placeholder="请选择虚拟机" filterable>
              <Option v-for="item in vmlists" :value="item.id" :key="item.id">{{item.name}}</Option>
            </Select>
          </FormItem>
          <FormItem  label="是否显示" prop="visibility">
            <RadioGroup v-model="allotFormValidate.visibility">
              <Radio :label=1>显示</Radio>
              <Radio :label=0>不显示</Radio>
            </RadioGroup>
            <span style="color:#f90" v-if="type == 4"> <Icon type="ios-information-circle-outline"/>用于在演练页面的展示控制</span>
            <span style="color:#f90" v-if="type == 1"> <Icon type="ios-information-circle-outline"/>用于在竞赛页面的展示控制</span>
          </FormItem>
        </Form>
      </Modal>-->
  </search-table>
</template>

<script>
  import {queryAllotTopoTargetList_old,allotTopoTarget_old,getTopoTargetList_old,delTopoTargetAllot_old,getSceneTeamTarget_old,changeAvailable_old} from '@/api/drill_compete'
  import {getaccessgrouplist} from '@/api/access_new'
  import { allDirection } from  '@/api/dict'
  import { debounce } from '@/libs/utils'

  export default {
    name: 'scenes',
    props:['type','disabledAllBtn'],
    components:{},
  data(){
    const validateNum = (rule, value, callback) => { //验证只能填入数字		    
          var reg = new RegExp("^([1-9]|[1-9]\\d|100)$");	     
          //验证警戒值		    
          if(value){		    	
            if (!reg.test(value)) {		        
              callback(new Error('请输入1-100的整数'));		    	
            }else{
              callback()
            }
          }else{
            callback()
          }
        }
      return {
        teamName: '',
        routeParams:{
            id:this.$route.query.id,
            prjid:this.$route.query.prjid
          },
          targetModal:{
            show:false,
            title:'目标分配',
            loading:true,
            type:1 //1添加，2修改
          },
          modifyTargetModal:{
            show:false,
            title:'修改分配',
            loading:true
          },
          pathList:[],
      accessGroupList:[],
          vmlists:[],
          allVms:[],
          teamlists:[],
      queryTargetTeamInfo:{
        pageIndex:1,
        pageSize:100000,
//				available:1
//				sceneId:this.$route.query.id,
        industry: '',
        projectId:this.$route.query.prjid
      },
      queryTargetAllotInfo:{
        pageIndex:1,
        pageSize:10,
        projectId:this.$route.query.prjid,
        sceneId:this.$route.query.id
      },
          questionList:[],
          access:'1',
          formValidate:{
          accessGroupList:[]
      },
          allotFormValidate:{
        "createTime": "",
        "externalIp": "",
        "externalPort": "",
        "externalServicePort": "",
        "id": "",
        "sceneId": "",
        "subnetId": "",
        "subnetName": "",
        "targetId": "",
        "targetName": "",
        "teamId": "",
        "teamName": "",
        "visibility": 0,
        "vmId": "",
        "vmName": ""
          },
          oldFormValidate:{},
          ruleValidate: {
        subnetId:[
              { required: true, message: '请选择子网络', trigger: 'change'}
            ],
            questionId:[
              { required: true, message: '请选择题目', trigger: 'change'}
            ],
            visibility:[
              { required: true, type:'number',message: '请选择', trigger: 'change'}
            ],
            vmId:[
              { required: true, message: '请选择虚拟机', trigger: 'change'}
            ],
            teamId:[
              { required: true, message: '请选择团队', trigger: 'change'}
            ],
            targetIds:[
              { required: true, type:"error",message: '请选择目标', trigger: 'change'}
            ],
            basicTargetId:[
              { required: true, message: '请选择目标', trigger: 'change'}
            ],
            idsTOS:[
              { required: true,type:'array',min:1, message: '请添加人员设备', trigger: 'change'}
            ]
          },
          querytime:{},
          targetTeamCol:[
  //        {
  //          type: 'index',
  //          align: 'center',
  //          ellipsis:true,
  ////          width:60
  //        },
          {
              title:'团队名称',
              key:'teamName',
              align:'center',
              ellipsis:true,
              tooltip:true,
              placement:'top-left',
          width: 240
//	            width:100
            },
            {
              title:'单位',
              key:'company',
              align:'center',
              ellipsis:true,
              tooltip:true,
          width: 100
  //          width:100
            },
            {
              title:'Url地址',
              key:'url',
              align:'center',
              ellipsis:true,
              tooltip:true,
              width: 300
            },
            {
              title:'行业',
              key:'industryName',
              align:'center',
              tooltip:true,
              width: 80
            },
            {
              title:'区域',
              key:'district',
              align:'center',
              tooltip:true,
              width: 66
            },
            {
              title:'创建时间',
              key:'createTime',
              align:'center',
              ellipsis:true,
  //          width:100
            },
            {
              title:'是否可用',
              key:'available',
              align:'center',
              ellipsis:true,
              tooltip:true,
              placement:'top-right',
              render:(h,params) => {
                return h('Poptip', {
									props: {
										confirm: true,
										'ok-text': "确定",
										'cancel-text': "取消",
										type: 'error',
										size: 'large',
										title: `你确定要${params.row.available == 1 ? '下线' : '上线'}目标吗?`,
										transfer:true
									},
									on: {
										'on-ok': () => {
											this.changeAvailable_old(params.row)
										}
									}
								}, [
									h('Button',{
                    props:{
                      type: params.row.available == 1 ? 'success' :'default',
                      size: 'small',
                      ghost: params.row.available == 1
                    }
                  },params.row.available == 1 ? '是' : '否' )
								])
              }
            },
            {
              title:'操作',
              key:'action',
              ellipsis:true,
              width:200,
              placement:'top-right',
              opList:[
                {
                    txt:'删除',
                    type:'delete',
                    tooltip:true,
                    disabled: () => this.disabledAllBtn,
                    fun:(data) => {
                        this.delTopoTargetAllot_old(data.id)
                    },
                    title: '你确定要删除吗?'
                }
              ],
//               render:(h,params)=>{
//                 return h('div',[

// //	                h('Button',{
// //	                  props:{
// //	                    type:'primary',
// //	                    size:'small'
// //	                  },
// //	                  style:{
// //	                    marginRight:'5px'
// //	                  },
// //	                  on:{
// //	                    click:()=>{
// //	                      //this.showAddAndUpdate(params.row)
// //	                      this.modifyTargetModal.show = true;
// //	                      this.allotFormValidate = JSON.parse(JSON.stringify(params.row));
// //	                      this.getAllVmlist();
// //	                    }
// //	                  }
// //	                },'修改'),
//                   h('Poptip', {
//                     props: {
//                       confirm: true,
//                       'ok-text': "确定",
//                       'cancel-text': "取消",
//                       type: 'error',
//                       size: 'large',
//                       title: '你确定要删除吗?',
//                       transfer:true
//                     },
//                     on: {
//                       'on-ok': () => {
//                         this.delTopoTargetAllot_old(params.row.id)
//                       }
//                     }
//                   }, [
//                       h('Button', {
//                         props: {
//                           type: 'error',
//                           size: 'small',
//                           disabled:this.disabledAllBtn
//                         },
//                         style: {
//                             border:'none',
//                 background:'none',
//                 boxShadow:'none'
//                         },
//                       }, [
//                         h('img', {
//                           attrs: {
//   //                          src: !this.setReBtnStatus(params.row) ?require('../../../assets/globalIcon/del.png'):require('../../../assets/globalIcon/dis-del.png'),
//                             src:this.disabledAllBtn ? require('../../../../assets/project/delNote-d.png') : require('../../../../assets/project/delNote-h.png')
//                           },
//                           style: {
//                               cursor: 'pointer',
//   //				                            'margin-right':'5px',
//                               'vertical-align': 'middle',
//   //				                            width:'16px',
//   //				                            height:'auto',
//                               display:'inline-block',
//                               marginBottom:'4px',
//                           },
//                       }),
// //	                    h('span',{
// //	                        style: {
// //	                            cursor: 'pointer',
// //	//                          color:!this.setReBtnStatus(params.row) ? '#2d8cf0' : '#c5c8ce'
// //															color:'#2d8cf0'
// //	                        },
// //	                    },'删除')
//                     ])
//                   ])
//                 ])
//               }
            }
          ],
          idsTOSCol:[
            {
              title:'团队',
              key:'teamName',
              align:'center',
              ellipsis:true,
              tooltip:true,
            },
            {
              title:'子网络',
              key:'subnetName',
              align:'center',
              ellipsis:true,
              tooltip:true,
            },
            {
              title:'虚拟机',
              key:'vmName',
              align:'center',
              ellipsis:true,
              tooltip:true,
            },
//	          {
//	            title:'外网IP',
//	            key:'externalIp',
//	            align:'center',
//	            ellipsis:true,
//	            tooltip:true,
//	          },
//	          {
//	            title:'外网端口',
//	            key:'externalPort',
//	            align:'center',
//	            ellipsis:true,
//	            tooltip:true,
//	          },
            {
              title:'显示状态',
              key:'score',
              align:'center',
              ellipsis:true,
              tooltip:true,
              render:(h,params) => {
          return h('Tag',{
            props:{
              color:params.row.visibility == 1 ? 'success' :'default',
              type:"border"
            },
            on:{
                        click:()=>{
                          //this.showAddAndUpdate(params.row)
                        }
                    }
          },params.row.visibility == 1 ? '是' : '否' )
        }
            },
            {
              title:'操作',
              key:'os',
              ellipsis:true,
//	            width:200,
              render:(h,params)=>{
                return h('div',[
                  h('Button',{
                    props:{
                      type:'primary',
                      size:'small'
                    },
                    style:{
                      marginRight:'5px'
                    },
                    on:{
                      click:()=>{
                          let index = this.formValidate.idsTOS.findIndex(item => item.id == params.row.id);
                          this.formValidate.idsTOS.splice(index,1);
                      }
                    }
                  },'移除')
                ])
              }
            }
          ],
          targetTeamData:[],
          targetTeamTotal:0,
          TargetId:'',
          projectInfo:{},
          subnetList:[],
          networkId:'',
          teamArr:[],
          networkArr:[],
          vmArr:[],
          idwithName:{},
          targetAllotList:[],
          targetAllotTotal:0,
          targetTeamDataCopy:[],
          industryList: []
      }	
  },
  filters:{

  },
  computed:{
    showQuestionList(){ //选出部署了题目镜像虚拟机的题目
      let quesList = [];
      this.questionList.forEach(ques => {
        if(this.allVms.map(vm => vm.imageName).includes(ques.imageName)){
          quesList.push(ques)
        }
      })
      return quesList;
    }
  },
  async mounted(){
      await this.getIndustryTypes()
      this.getAccessGroupList();
      this.getAllTargetTeam();
      this.queryTargetAllot();
  },
    methods:{
      // 分配目标的模态框关闭后清空搜索条件
      targetModalVisibleChange(type) {
        if (!type) {
          this.queryTargetTeamInfo.industry = ''
          this.teamName = ''
        }
      },
      // 防抖封装，团队名改变时，延迟更新列表数据
      getDataBounce: debounce(function() {
          this.getAccessGroupList()
      }),
      // 获取行列列表
      getIndustryTypes() {
        return new Promise(resolve => {
          allDirection({ dictTypeID: 'hwIndustryTypes' }).then(({ code, message, attribute = {} }) => {
            attribute = attribute.attribute || []
            if (code !== 1) {
              this.$Message.warning(message)
              return
            }
            let list = []
            attribute.forEach(item => list = list.concat(item.dictEntryList))
            this.industryList = list
          }).catch(() => {
            this.$Message.error('获取行业列表异常')
          }).finally(() => {
            resolve()
          })
        })
      },
//  	getProjectInfo(){
//			getstatusbyprjid(this.$route.query.prjid).then(data => {
//				if(data.code == 1){
//					this.projectInfo = data.attribute;
//					this.getProjectSubnet();
//				}
//			})
//		},
    getTargetTeamList(group){
      this.queryTargetTeamInfo.company = group ? group.queryCompany :'';
        getTopoTargetList_old(this.queryTargetTeamInfo).then(data => {
          if(data.code==1){
//	  				this.targetTeamData = data.data.items || data.data;
//	  				this.targetTeamDataCopy = data.data.items || data.data;
//	  				this.targetTeamData.forEach(team => {
//	  					this.idwithName[team.id] = team;
//					})
            if(!group){
              this.formValidate.accessGroupList.forEach(group => {
                group.targetTeamData = data.data.items|| data.data;
              })
            }else{
              group.targetTeamData = data.data.items|| data.data;
            }
            this.targetTeamTotal = data.data.total;
          }else{
            
          }
        })
      },
      getAllTargetTeam(){
        let params = {
          pageIndex:1,
        pageSize:2147483646,
        projectId:this.$route.query.prjid
        }
        getTopoTargetList_old(params).then(data => {
          if(data.code==1){
            data.data.items.forEach(team => {
              this.idwithName[team.id] = team;
          })
          }
        })
      },
      changeTargetTeamPage(page,group){
        group.queryPage = page;
        this.queryTargetTeamInfo.pageIndex = page;
        this.getTargetTeamList(group);
      },
      initData(){
        this.formValidate = {
          accessGroupList:[]
      }
      },
      getAllVmlist(){
        let _this = this;
          let params = {
        page:1,
        pageSize:10000,
        sortBy:'name',
        order:'asc',
        findPorts:true,
      }
          if(this.formValidate.targetId){
            params.imageId = this.idwithName[this.formValidate.targetId].imageId;
          }
          if(this.allotFormValidate.basicTargetId){
            params.imageId = this.idwithName[this.allotFormValidate.basicTargetId].imageId;
          }
          if(this.group){
            //params.party = this.group.partyId;
          }
          if(this.targetModal.show && this.formValidate.subnetId){
            params.networkId = this.formValidate.subnetId;
          }
          if(this.modifyTargetModal.show && this.allotFormValidate.subnetId){
            params.networkId = this.allotFormValidate.subnetId;
          }
          if(this.modifyTargetAllot.show && this.allotFormValidate.subnetId){
            params.networkId = this.allotFormValidate.subnetId;
          }
      queryVmWithParty(this.routeParams.prjid,params).then(data => {
//		    getProjectSevers(params).then(data => {
        if(data.code == 1){
          this.vmlists = data.data.list || data.data;
          if(this.targetModal.show && this.vmlists.length > 0){
              this.formValidate.vmId = this.vmlists[0].id;
              this.formValidate.vmName = this.vmlists[0].name;
//			    		this.queryTargetAllotRelation();
    //	    		this.formValidate.idsTOS = [];
            }else if(this.modifyTargetModal.show && this.vmlists.length > 0){
//			       	    _this.$nextTrick(() => {
//			       	    	
//			       	    })
//			    		setTimeout(() => {
//			    			this.allotFormValidate.vmId = this.vmlists[0].id;
//			    			this.allotFormValidate.vmName = this.vmlists[0].name;
//			    		},500)
            }
          this.vmlists.forEach(vm => {
            this.idwithName[vm.id] = {
              id:vm.id,
              name:vm.name
            }
          })
          //this.getVmIp(this.formValidate.vmId);
//					if(this.vmlists.length > 0){
//						let server = this.vmlists.filter(vm => vm.id == this.formValidate.vmId)[0];
//	    		        if(server){
//	    		        	this.formValidate.subnet = server.addresses[0].subnetId;
//	    		        	this.getFlagServerList(server.address[0].ipv4);
//	    		        	this.getFlagServerList(server.addresses[0].ip);
//	    		        }
//					}
        }
      })
    },
    getAccessGroupList(){
      if(!this.routeParams.id){
        return;
      }
      let params = {
        pageIndex:1,
        pageSize:2147483647,
        testId:this.routeParams.id,
        name: this.teamName
      };
      this.selectGroupList = [];
      this.formValidate.accessGroupList = [];
      getaccessgrouplist(params).then(data => {
        if(data.code == 1){
          this.accessGroupList = data.data.items;
          this.formValidate.accessGroupList = data.data.items.filter(item => item.name !== '目标方管理员组' && item.creatorName !='内部服务用户');
          this.formValidate.accessGroupList.forEach(group => {
            this.$set(group,'targetIds',[]);
            this.$set(group,'selectableTargets',[]);
            this.$set(group,'targetTeamData',[]);
            this.$set(group,'queryCompany','');
            this.$set(group,'queryPage',1);
          })
          this.getTargetTeamList();
          this.getSceneTeamTarget_old();
        }else if(data.code == -2) {
          this.accessGroupList = [];
        }else{
          this.$Message.warning(data.message);
        }
      })
    },
    showAddAndUpdate(info){
      this.targetModal.show = true;
      this.formValidate.accessGroupList.forEach(item => {
        item.targetIds = [];
      });
      this.getAccessGroupList();
      if(this.targetAllotTotal > 0){
      }
      if(!info){
        this.targetModal.type = 1;
      }else{
        this.targetModal.type = 2;
      }
    },
      handleReset (name) {
//	        this.$refs[name].resetFields();
          this.addTarget = false;
          this.initData();
          this.$refs [name].fields.forEach(function (e) {
          if (e.fieldValue != undefined && e.fieldValue!='') {
                e.resetField()
            }
      })
      },
      addTargetTeam(){
        let params = JSON.parse(JSON.stringify(this.formValidate));
        params.questionName = this.question.name;

      },
      modifyTargetTeam(){
        let params = JSON.parse(JSON.stringify(this.formValidate));
        params.questionName = this.question.name;

      },
      saveTargetTeam(){
        this.$refs['formValidate'].validate((valid) => {
              if (valid) {
                if(this.targetModal.type == 1){
                  this.addTargetTeam();
                }else{
                  this.modifyTargetTeam();
                }
              }else{
                this.cancelLoading('targetModal');
              }
          })
      },
      getTargetSize(size){
          this.queryTargetAllotInfo.pageSize = size;
          this.queryTargetAllot();
      },
      getTargetPage(page){
          this.queryTargetAllotInfo.pageIndex = page;
          this.queryTargetAllot();
      },
      changeTeamGroup(){
        
      },
      changeTarget(targetId){
        if(this.targetModal.show){
          this.formValidate.vmId = '';
          this.formValidate.vmName = '';
          this.formValidate.subnetId = '';
          this.formValidate.subneName = '';
          this.formValidate.teamId = '';
          this.formValidate.teamName = '';
          this.queryTargetAllotRelation();
        }else if(this.modifyTargetModal.show){
          this.allotFormValidate.vmId = '';
          this.allotFormValidate.vmName = '';
        }
        this.getAllVmlist();
      },
      changeSubnet(id){
        if(!id){
          return;
        }
//	    	if(this.targetModal.show){
//	    		this.formValidate.vmId = '';
//	    		this.formValidate.vmName = '';
//	    		this.queryTargetAllotRelation();
////	    		this.formValidate.idsTOS = [];
//	    	}else if(this.modifyTargetModal.show){
//	    		this.allotFormValidate.vmId = '';
//	    		this.allotFormValidate.vmName = '';
//	    	}
      this.formValidate.externalIp = this.idwithName[this.formValidate.subnetId].ip;
        this.getAllVmlist();
      },
      changeVm(){
        
      },
      getProjectSubnet(){
        queryNetworkList(this.$route.query.prjid,this.projectInfo.network.id).then(data => {
          if(data.code == 1){
            let subnetList = [];
            let linkList = [];
            data.attribute.editorStage.childs.forEach(item => {
              subnetList = subnetList.concat(item.childs);
              if(item.links){
                linkList = linkList.concat(item.links);
              }
            })
            this.subnetList = subnetList.filter(subnet => subnet.dataType == 'NW');
            this.subnetList.forEach(subnet => {
              let ip;
              if(this.type == 1){
                if(linkList.filter(link => link.rightNetId == subnet.id).length > 0){
                  ip = linkList.filter(link => link.rightNetId == subnet.id)[0].rightIpParts[0].ipAddress; //新接口这个字段没有了
                }
              }
            this.idwithName[subnet.id] = {
              id:subnet.id,
              name:subnet.name,
              ip:ip
            }
          })
          }
        })
      },
      addIdTOS(){
        this.$refs['addFormValidate'].validate((valid) => {
              if (valid) {
//	            	if(this.targetModal.type == 1){
//	            		this.addTargetTeam();
//	            	}else{
//	            		this.modifyTargetTeam();
//	            	}
          this.formValidate.idsTOS.push({
              "vmId":this.idwithName[this.formValidate.vmId].id,
            "vmName":this.idwithName[this.formValidate.vmId].name,
            "teamId":this.idwithName[this.formValidate.teamId].id,
                "teamName":this.idwithName[this.formValidate.teamId].name,
                "subnetId":this.formValidate.subnetId,
              "subnetName":this.idwithName[this.formValidate.subnetId].name,
            "externalIp":this.formValidate.externalIp, //对外ip
            "externalPort": this.formValidate.externalPort, //对外端口
            "externalServicePort":this.formValidate.externalServicePort,
            "visibility": this.formValidate.visibility
            })
//	            }else{
////	            	this.cancelLoading('targetModal');
              }
          })
    },
    targetAllot(){
        this.$refs['formValidate'].validate((valid) => {
              if (valid) {
                let sceneId = this.$route.query.id;
              let params = this.formValidate.accessGroupList.map(group => {
                return {
                "projectId": this.$route.query.prjid,
                "sceneId": sceneId,
                "targets": group.targetIds.map(id => {
                  return {
                    "company": this.idwithName[id].company,
                      "tagetId": id
                  }
                }),
                "teamId": group.id,
                "teamName":group.name
            }
              })
              allotTopoTarget_old(params, sceneId).then(data => {
                if(data.code == 1){
              // 添加成功后清空搜索条件，回退到首页
              this.queryTargetAllotInfo.pageIndex = 1
              this.queryTargetAllotInfo.teamName = ''
              this.queryTargetAllotInfo.company = ''
              this.queryTargetAllotInfo.url = ''
                  this.$emit('add-data')
                  this.queryTargetAllot();
                  this.targetModal.show = false;
//			   	    		this.formValidate.vmId = '';
//			   	    		this.formValidate.teamId = '';
//			   	    		this.formValidate.visibility = 0;
                }else{
                  this.$Message.warning(data.message);
                  this.cancelLoading('targetModal');
                }
              }).catch(error => {
                this.$Message.error(error);
                this.cancelLoading('targetModal');
              })
          }else{
            this.cancelLoading('targetModal');
          }
        })
    },
    VRIPRelation(){
        let params = this.formValidate.idsTOS.map(item => {
          return {
            "contestId": this.$route.query.id,
            "ip": this.idwithName[this.formValidate.targetId].ip,
            "targetName":this.idwithName[this.formValidate.targetId].name,
            "teamId": item.teamId,
            "teamName": item.teamName,
            "virtualRouterIP": item.externalIp,
            "vmname": item.vmName
        }
        })
          VRIPRelation(params).then(data => {
            if(data.code == 1){
              
            }
        })
    },
    //queryTargetAllot,queryTargetAllotRelation,modifyTargetAllot
    queryTargetAllot(){
        queryAllotTopoTargetList_old(this.queryTargetAllotInfo).then(data => {
          if(data.code == 1){
            let list = data.data.items
            this.targetAllotList = list.map(item => {
              item.industryName = this.getIndustryName(item.industry)
              return item
            })
            this.targetAllotTotal = data.data.total;
          }else{
            this.$Message.warning(data.message);
          }
        }).catch(error => {
          this.$Message.error(error);
        })
    },
    // 将行业Id转换为对应的名称
    getIndustryName(industryId) {
      let item = this.industryList.find(item => item.dictid === industryId)
      // 返回对应的名称，没有查到数据，还是返回ID
      return item ? item.dictname : industryId
    },
    queryTargetAllotRelation(){
        let params = {
            pageIndex:1,
            pageSize:1000,
//	   	   	   subnetId:this.formValidate.subnetId,
            basicTargetId:this.formValidate.targetId,
            sceneId:this.$route.query.id
        }
        queryTargetAllotRelation(params).then(data => {
          if(data.code == 1){
            this.formValidate.idsTOS = data.data.items;
//	   				if(data.data.items.length > 0){
//	   					this.formValidate.subnetId = data.data.items[0].subnetId;
//	   					this.formValidate.subnetName = data.data.items[0].subnetName;
//	   					this.getAllVmlist();
//	   				}
          }else{
          this.$Message.warning(data.message);
          }
          }).catch(error => {
          this.$Message.error(error);
        })
    },
    modifyTargetAllot(){
          this.$refs['allotFormValidate'].validate((valid) => {
              if (valid) {
            let params = {
                "createTime":this.allotFormValidate.createTime,
            "externalIp": this.allotFormValidate.externalIp,
            "externalPort": this.allotFormValidate.externalPort,
            "externalServicePort":this.allotFormValidate.externalServicePort,
            "id": this.allotFormValidate.id,
            "sceneId": this.allotFormValidate.sceneId,
            "subnetId": this.allotFormValidate.subnetId,
            "subnetName": this.idwithName[this.allotFormValidate.subnetId].name,
            "basicTargetId": this.allotFormValidate.basicTargetId,
            "targetName": this.idwithName[this.allotFormValidate.basicTargetId].name,
            "teamId": this.allotFormValidate.teamId,
            "teamName": this.idwithName[this.allotFormValidate.teamId].name,
            "visibility": this.allotFormValidate.visibility,
            "vmId": this.allotFormValidate.vmId,
            "vmName": this.idwithName[this.allotFormValidate.vmId].name,
            }
            modifyTargetAllot(params.id,params).then(data => {
                if(data.code == 1){
                  this.$emit('update-data')
                  this.queryTargetAllot();
                  this.modifyTargetModal.show = false;
                  this.cancelLoading('modifyTargetModal');
                  this.$Message.info('操作成功');
                }else{
              this.$Message.warning(data.message);
              }
              }).catch(error => {
              this.$Message.error(error);
              this.cancelLoading('modifyTargetModal');
            })
          }else{
            this.cancelLoading('modifyTargetModal');
          }
          })
    },
    cancelLoading(name){
        this[name].loading = false;
          setTimeout(() => {
            this[name].loading = true;
          })
      },
      closeTargetModal(){
        this.addTarget = false;
//	    	this.handleReset('formValidate');
//	    	this.handleReset('addFormValidate');
      },
      delTopoTargetAllot_old(id){
        delTopoTargetAllot_old(id).then(data => {
          if(data.code == 1){
            this.$Message.info('删除成功')
          // 删除后展示当前页，当前页没有数据展示前一页
          this.queryTargetAllotInfo.pageIndex = (this.targetAllotList.length == 1 && this.queryTargetAllotInfo.pageIndex > 1) ?
              this.queryTargetAllotInfo.pageIndex - 1 : this.queryTargetAllotInfo.pageIndex;
            this.$emit('delete-data')
            this.queryTargetAllot();
            this.$refs.searchTable.delSelectItem(id);
          } else {
            this.$Message.warning(data.message)
          }
        }).catch(() => {
          this.$Message.error('删除异常')
        })
      },
      getSceneTeamTarget_old(){
        getSceneTeamTarget_old(this.$route.query.id).then(data => {
          if(data.code ==1 && data.data.items.length > 0){
            this.formValidate.accessGroupList.forEach(group => {
              let team = data.data.items.filter(item => item.teamId == group.id);
              if(team.length > 0){
                group.targetIds = [...new Set(team[0].targets.map(target => target.tagetId))];
              }
            })
//	    			this.formValidate.accessGroupList = data.data.items.map(item => {
//	    				return {
//	    					id:item.teamId,
//	    					name:item.teamName,
//	    					targetIds:item.targets.map(target => target.tagetId)
//	    				}
//	    			});
            //this.changeTarget()
          }
        })
      },
      changeAvailable_old(item){
        changeAvailable_old(item.id,{available:!item.available}).then(data => {
          if(data.code == 1){
            this.$Message.info('操作成功')
            this.queryTargetAllot();
          } else {
            this.$Message.warning(data.message)
          }
        }).catch(() => {
          this.$Message.error('操作异常')
        })
      },
      changeTarget(){
      let selectedTargets = [];
        this.formValidate.accessGroupList.forEach(group => {
          selectedTargets = selectedTargets.concat(group.targetIds); //所有已经选择过得目标
        })
        let unSelectableTargets = this.targetTeamDataCopy.filter(target => !selectedTargets.includes(target.id)).map(target => target.id);
        this.formValidate.accessGroupList.forEach(group => {
          group.selectableTargets = [...unSelectableTargets,...group.targetIds].map(id => {
            return this.idwithName[id];
          });
        })
      },
      changeCompanySelect(curTargetIds,curGroup){ 
        this.formValidate.accessGroupList.forEach(group => {
          if(group.id != curGroup.id){
            group.targetTeamData.forEach(target => {
              if(curTargetIds.includes(target.id) && group.targetIds.includes(target.id) && !target.publicTarget){//选中时，取消其他组此目标的选中
                group.targetIds.splice(group.targetIds.findIndex(id => id == target.id),1);
                
              }
            })
          }
        })
      }
    }
}
</script>

<style>
  .drillsTable .ivu-poptip-body {
    text-align: left!important;
  }
  .scenesHeader{
    margin-bottom: 16px;
  }
  .drillTables{
    min-height: 300px;
  }
  .drillsTable.ivu-table-wrapper{
    overflow: inherit;
  }
</style>
<style scoped>
  .targetHeader{
    /*padding: 10px;*/
    margin:15px 0px;
  }
  .account-target-modal /deep/ .ivu-modal {
    height: calc(100vh - 200px);
    min-height: 520px;
  }
  .account-target-modal /deep/ .ivu-modal .ivu-modal-content {
    height: 100%;
  }
  .account-target-modal /deep/ .ivu-modal .ivu-modal-content .ivu-modal-body {
    height: calc(100% - 112px);
  }
  .search-group {
    width: calc(100% + 32px);
    margin-left: -16px;
    padding-bottom: 16px;
    border-bottom: 1px solid #e8eaec;
  }
  .account-target-modal /deep/ .ivu-modal .ivu-modal-content .ivu-modal-body>form {
    height: calc(100% - 65px);
    overflow: auto;
  }
</style>
